package ntu.edu.cn;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Fenghua Qiu on 8/4/2016.
 */
public class ClientLogin {

    public static CloseableHttpClient init() {

        HttpPost httppost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Default.aspx");
//        HttpHost proxy = new HttpHost("172.17.20.227",9090);
//        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//        httppost.setConfig(config);
        CloseableHttpClient httpclient = null;
        try {
            httpclient = DownloadYZM.downloadFile();
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("__VIEWSTATE", "/wEPDwUJODExMDE5NzY5ZGRgtUdRucUbXsT8g55XmVsTwV6PMw=="));
            formparams.add(new BasicNameValuePair("__VIEWSTATEGENERATOR", "6C0FF253"));
            formparams.add(new BasicNameValuePair("xh", "1213022087"));
            formparams.add(new BasicNameValuePair("sfzh", "320525199312217410"));
            formparams.add(new BasicNameValuePair("kl", "320525199312217410"));
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("please enter the YZM...");
            String yan = br.readLine();
            formparams.add(new BasicNameValuePair("yzm", yan));
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(entity1);
            HttpClientContext context = HttpClientContext.create();
            HttpResponse response1 = httpclient.execute(httppost, context);
            HttpEntity entity = response1.getEntity();
            String html = EntityUtils.toString(entity, "utf-8");

            System.out.println("the httppost responsen status is " + response1.getStatusLine());
            // System.out.println("Initial set of cookies:" + entity);
            //  String set_cookie = response1.getFirstHeader("Set-Cookie").getValue();
            // System.out.println("*****************"+set_cookie.substring(0,set_cookie.indexOf(";")));
            //System.out.println(html);
//
            //String  rede  = response1.getFirstHeader("location").getValue();
            String location = "http://jwgl.ntu.edu.cn/cjcx/Main.aspx";
//                List<URI> list = context.getRedirectLocations();
//                String location = "";
            System.out.println("ready to redirect  a  new URI +  " + location);
            if (location != null && !"".equals(location)) {
                // location =list.get(0).toASCIIString();
                // System.out.println(list.get(0).toASCIIString());

                HttpGet httpGet = new HttpGet(location);

                httpGet.setHeader("Accept", "text/html, application/xhtml+xml, */*");
                httpGet.setHeader("Referer", "http://jwgl.ntu.edu.cn/cjcx/Default.aspx");

                httpGet.setHeader("Accept-Language", "en-US");
                httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
                httpGet.setHeader("Accept-Encoding", "gzip,deflate");
                httpGet.setHeader("Proxy-Connection", "Keep-Alive");
                httpGet.setHeader("DNT", "1");
                httpGet.setHeader("HOST", "jwgl.ntu.edu.cn");
                httpGet.setHeader("Pragma", "no-cache");
                httpGet.setHeader("Content-Length", "0");


                HttpResponse response = httpclient.execute(httpGet);
                System.out.println(response.getStatusLine().getStatusCode());
                String hl = EntityUtils.toString(response.getEntity());
                //System.out.println(hl);


//                httpclient.setRedirectHandler(new DefaultRedirectStrategy() {
//                    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
//                        boolean isRedirect = false;
//                        try {
//                            isRedirect = super.isRedirected(request, response, context);
//                        } catch (ProtocolException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                        if (!isRedirect) {
//                            int responseCode = response.getStatusLine().getStatusCode();
//                            if (responseCode == 301 || responseCode == 302) {
//                                return true;
//                            }
//                        }
//                        return isRedirect;
//                    }


                //  List<Cookie> cookies = cookieStore.getCookies();
//                System.out.println("cccccccccccccccccccccc" + cookies);
//                if (cookies.isEmpty()) {
//                    System.out.println("None");
//                } else {
//                    for (int i = 0; i < cookies.size(); i++) {
//                        System.out.println("- " + cookies.get(i).toString());
//                    }
//                }
            }

        } catch (Exception e) {

        } finally {
        }
        return httpclient;
    }

    public void QueryAll(CloseableHttpClient httpClient) {
        //HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/QueryAll.aspx");
        HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Data/ScoreAllData.aspx");
        try {
            HttpResponse re = httpClient.execute(httpPost);
            String entity = EntityUtils.toString(re.getEntity());
            System.out.println(entity);
        } catch (Exception e) {
            System.out.println("something is error to get data  ");
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * test offsetscore
     * @param httpClient
     */
    public static void QueryOffSetScore(CloseableHttpClient httpClient) {
        //HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/QueryAll.aspx");
        HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Data/ScoreOffsetData.aspx");

        try {
            HttpResponse re = httpClient.execute(httpPost);
            String entity = EntityUtils.toString(re.getEntity());
            System.out.println(entity);
        } catch (Exception e) {
            System.out.println("something is error to get data  ");
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * search dep
     * @param httpClient
     */
    public static void QueryDep(CloseableHttpClient httpClient){
        HttpGet httpGet = new HttpGet("http://jwgl.ntu.edu.cn/cjcx/Data/Basis/dep.aspx?_dc=1471227774212");
        try{
            HttpResponse re = httpClient.execute(httpGet);
            String entity = EntityUtils.toString(re.getEntity());
            System.out.println(entity);
        }catch (Exception e){
            System.out.println("something is error to get data  QueryDep");
            e.printStackTrace();
        }
    }

    /**
     * Search class
     * @param httpClient
     */
    public static void QueryClass(CloseableHttpClient httpClient){
        HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Data/Basis/class.aspx");
        List<NameValuePair> params = new ArrayList();
        params.add(new BasicNameValuePair("depId", "19"));
        try{
        UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(params, "UTF-8");
        httpPost.setEntity(entity1);
            HttpResponse re = httpClient.execute(httpPost);
            String entity = EntityUtils.toString(re.getEntity());
            System.out.println(entity);
        }catch (Exception e){
            System.out.println("something is error to get data QueryClass");
            e.printStackTrace();
        }
    }

    /**
     * query timetable
     * @param httpClient
     */
    public static void queryTimetable(CloseableHttpClient httpClient){
        HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Data/Table/ClassTableData.aspx");
        List<NameValuePair> params = new ArrayList();
        params.add(new BasicNameValuePair("xq", "2015-2016-2"));
        params.add(new BasicNameValuePair("bjid","3015"));
        try{
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(entity1);
            HttpResponse re = httpClient.execute(httpPost);
            String entity = EntityUtils.toString(re.getEntity());
            System.out.println(entity);
        }catch (Exception e){
            System.out.println("something is error to get data timetable");
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        CloseableHttpClient client = init();
        QueryOffSetScore(client);
        System.out.println("search dep");
        QueryDep(client);
        System.out.println("search class");
        QueryClass(client);
        System.out.println("search timetable");
        queryTimetable(client);
    }


}
